package com.mc.read.pcApi.service;

import com.alibaba.fastjson.JSON;
import com.mc.read.common.constant.Constants;
import com.mc.read.common.emun.ServiceCodeEnum;
import com.mc.read.common.exception.ServiceException;
import com.mc.read.dao.mapper.*;
import com.mc.read.dao.models.*;
import com.mc.read.dao.vo.BookTypeLabel;
import com.mc.read.dao.vo.MainVo;
import com.mc.read.vo.request.BaseRequest;
import com.mc.read.vo.respose.BaseRespose;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author liuhao
 * @date 2019/6/10 18:37
 */
@Service
@Slf4j
public class MainInfoService {

    @Autowired
    UserinformationMapper userinformationMapper;
    @Autowired
    BookinformationMapper bookinformationMapper;
    @Autowired
    BooklabelMapper booklabelMapper;
    @Autowired
    UserbooklabelMapper userbooklabelMapper;
    @Autowired
    UserinformationdetMapper userinformationdetMapper;
    @Autowired
    BooktypeMapper booktypeMapper;
    @Autowired
    SecondleveltypeforuserMapper secondleveltypeforuserMapper;
    @Autowired
    ReadtimeMapper readtimeMapper;
    @Autowired
    FunctionService functionService;
    @Autowired
    AdvertisingMapper advertisingMapper;
    @Autowired
    HotMapper hotMapper;


    /**
     * @Author:LiuHao
     * @Date:15:24 2019/5/31
     * 查询主页信息 selectMainInfo
     **/
    public BaseRespose selectMainInfo(BaseRequest baseRequest) {
        log.info("查询主页信息,参数为{}", JSON.toJSONString(baseRequest));
        BaseRespose baseRespose = new BaseRespose();
        MainVo mainVo = new MainVo();
        Bookinformation bookinformationRequest = null;
        try {
            bookinformationRequest = JSON.parseObject(JSON.toJSONString(baseRequest.getRequestString()), Bookinformation.class);
        } catch (Exception e) {
            throw new ServiceException(ServiceCodeEnum.INFO_IS_FAIL, JSON.toJSONString(baseRequest));
        }
        Bookinformation bookinformation = null;
        //查询个人信息
        Userinformationdet userinformation = userinformationdetMapper.selectByUserId(baseRequest.getUserId());
        mainVo.setUserinformation(userinformation);
//        if (ObjectUtils.isEmpty(bookinformationRequest.getBookinformationid())) {
//            //证明不是从本插件进去的
//            BookinformationExample example = new BookinformationExample();
//            example.createCriteria().andBooknameEqualTo(bookinformationRequest.getBookname()).andAuthorEqualTo(bookinformationRequest.getAuthor());
//            List<Bookinformation> bookinformationList = bookinformationMapper.selectByExample(example);
//            if (bookinformationList.size() > 0) {
//                bookinformation = bookinformationList.get(0);
//            }
//        } else {
//            bookinformation = bookinformationMapper.selectByPrimaryKey(bookinformationRequest.getBookinformationid());
//        }
        BookinformationExample example = new BookinformationExample();
        example.createCriteria().andBooknameEqualTo(bookinformationRequest.getBookname()).andAuthorEqualTo(bookinformationRequest.getAuthor()).andDeletemarkEqualTo(0);
        List<Bookinformation> bookinformationList = bookinformationMapper.selectByExample(example);
        if (bookinformationList.size() > 0) {
            bookinformation = bookinformationList.get(0);
        }
        //有这本书
        if (!ObjectUtils.isEmpty(bookinformation)) {
            BooklabelCustom booklabelCustom = new BooklabelCustom();
            booklabelCustom.setBookid(bookinformation.getBookinformationid());
            booklabelCustom.setUserid(baseRequest.getUserId());
            //查询标签详情
            List<BooklabelCustom> booklabelCustomList = booklabelMapper.selectLabelList(booklabelCustom);
            //返回标签的详情
            mainVo.setBooklabelCustomList(booklabelCustomList);
            BookinformationCustom bookinformationCustom = new BookinformationCustom();
            BeanUtils.copyProperties(bookinformation, bookinformationCustom);
            bookinformationCustom.setLimit(Constants.MAIN_VIP);
            //查询两本vip的
            List<Bookinformation> vipList = bookinformationMapper.selectVipList(bookinformationCustom);
            //取到的书籍
            List<Bookinformation> bookinformations = new ArrayList<>();
            bookinformations.addAll(vipList);

            //已经取到的Id集合
            List<Integer> bookIdList = new ArrayList<>();
            bookIdList.add(bookinformation.getBookinformationid());
            for (Bookinformation book : vipList
                    ) {
                bookIdList.add(book.getBookinformationid());
            }
            //查询标签书籍 最多4个
            bookinformationCustom.setLimit(Constants.MAIN_SUM - vipList.size());
            bookinformationCustom.setSumLimit(Constants.MAIN_SELECT);
            bookinformationCustom.setBookIdList(bookIdList);
            List<Bookinformation> labelList = selectBookByLabel(bookinformationCustom);
            bookinformations.addAll(labelList);
            //如果够数量了
            if (bookinformations.size() >= Constants.MAIN_SUM) {
                mainVo.setBookinformationList(bookinformations);
            } else {
                //标签推荐没拿够 则在类型中取
                for (Bookinformation book : labelList
                        ) {
                    bookIdList.add(book.getBookinformationid());
                }
                bookinformationCustom.setBookIdList(bookIdList);
                bookinformationCustom.setLimit(Constants.MAIN_SUM - bookinformations.size());
                //查询类别中的书籍
                List<Bookinformation> bookList = selectBookByBookType(bookinformationCustom);
                bookinformations.addAll(bookList);
                if (bookinformations.size() >= Constants.MAIN_SUM) {
                    mainVo.setBookinformationList(bookinformations);
                } else {
                    //从点击量前50随便拿基本
                    bookinformationCustom.setLimit(Constants.MAIN_SUM - bookinformations.size());
                    bookinformationCustom.setSumLimit(Constants.RAN_SELECT);
                    for (Bookinformation book : bookList
                            ) {
                        bookIdList.add(book.getBookinformationid());
                    }
                    bookinformationCustom.setBookIdList(bookIdList);
                    bookList = selectBookByRandom(bookinformationCustom);
                    bookinformations.addAll(bookList);
                    mainVo.setBookinformationList(bookinformations);
                }
            }
            mainVo.setBookinformation(bookinformation);
            //更新小说的点击量
            bookinformationMapper.updateReadNum(bookinformation.getBookinformationid());
            //查询是否存在二级分类
            if (ObjectUtils.isEmpty(bookinformation.getSecondlevelid())) {
                SecondleveltypeforuserExample userExample = new SecondleveltypeforuserExample();
                userExample.createCriteria().andBookidEqualTo(bookinformation.getBookinformationid()).andUseridEqualTo(baseRequest.getUserId());
                List<Secondleveltypeforuser> secondleveltypeforuserList = secondleveltypeforuserMapper.selectByExample(userExample);
                //证明该用户对该书籍选举
                if (secondleveltypeforuserList.size() == 0) {
                    BooktypeExample booktypeExample = new BooktypeExample();
                    booktypeExample.createCriteria().andParentidEqualTo(bookinformation.getMainlevelid());
                    booktypeExample.setOrderByClause("sort");
                    List<Booktype> booktypeList = booktypeMapper.selectByExample(booktypeExample);
                    mainVo.setSecondlevelTypeList(booktypeList);
                }
            }

            //更新用户阅读的书籍
//            functionService.updateUserBook(baseRequest.getUserId(),bookinformation);

        } else {
            BookinformationCustom bookinformationCustom = new BookinformationCustom();
            bookinformationCustom.setSumLimit(Constants.RAN_SELECT);
            bookinformationCustom.setLimit(Constants.MAIN_SUM);
            mainVo.setBookinformationList(selectBookByRandom(bookinformationCustom));
            mainVo.setBooklabelCustomList(null);
        }


        //查询广告
        List<Advertising> advertisingList = advertisingMapper.selectAdverList();
        mainVo.setAdvertisingList(advertisingList);
        //查询热门品论
        Hot hot = hotMapper.selectByPrimaryKey(1);
        mainVo.setHot(hot);
        //查询主类
        List<Booktype> booktypeList=booktypeMapper.selectMainLevel();
        mainVo.setBooktypeList(booktypeList);
        baseRespose.setReturnString(mainVo);
        return baseRespose;
    }

    /**
     * @Author:LiuHao
     * @Date:15:24 2019/5/31
     * 推荐小说查询（换一批） selectOtherRecBook
     **/
    public BaseRespose selectOtherRecBook(BaseRequest baseRequest) {
        log.info("推荐小说查询（换一批）,参数为{}", JSON.toJSONString(baseRequest));
        BaseRespose baseRespose = new BaseRespose();
        BookinformationCustom bookinformationCustom = null;
        try {
            bookinformationCustom = JSON.parseObject(JSON.toJSONString(baseRequest.getRequestString()), BookinformationCustom.class);
        } catch (Exception e) {
            throw new ServiceException(ServiceCodeEnum.INFO_IS_FAIL, JSON.toJSONString(baseRequest));
        }
        //取到的书籍
        List<Bookinformation> bookinformations = new ArrayList<>();
        if (ObjectUtils.isEmpty(bookinformationCustom.getBookinformationid())) {
            bookinformationCustom.setSumLimit(Constants.RAN_SELECT * 4);
            bookinformationCustom.setLimit(Constants.REC_SUM);
            bookinformations = selectBookByRandom(bookinformationCustom);
        } else {
            Bookinformation bookinformation = bookinformationMapper.selectByPrimaryKey(bookinformationCustom.getBookinformationid());
            if (ObjectUtils.isEmpty(bookinformation)) {
                bookinformationCustom.setSumLimit(Constants.RAN_SELECT * 4);
                bookinformationCustom.setLimit(Constants.REC_SUM);
                bookinformations = selectBookByRandom(bookinformationCustom);
            } else {
                BeanUtils.copyProperties(bookinformation, bookinformationCustom);
                //已经取到的Id集合
                List<Integer> bookIdList = bookinformationCustom.getBookIdList();
                bookIdList.add(bookinformation.getBookinformationid());
                //查询vip数量
                bookinformationCustom.setLimit(Constants.REC_VIP);
                bookinformationCustom.setBookIdList(bookIdList);
                List<Bookinformation> vipList = bookinformationMapper.selectVipList(bookinformationCustom);
                bookinformations.addAll(vipList);
                for (Bookinformation book : vipList
                        ) {
                    bookIdList.add(book.getBookinformationid());
                }
                //查询标签书籍 最多4个
                bookinformationCustom.setLimit(Constants.REC_LABEL);
                bookinformationCustom.setSumLimit(Constants.REC_SELECT);
                bookinformationCustom.setBookIdList(bookIdList);
                List<Bookinformation> labelList = selectBookByLabel(bookinformationCustom);
                bookinformations.addAll(labelList);
                for (Bookinformation book : labelList
                        ) {
                    bookIdList.add(book.getBookinformationid());
                }
                bookinformationCustom.setBookIdList(bookIdList);
                bookinformationCustom.setLimit(Constants.REC_LEVEL);
                //查询类别中的书籍
                List<Bookinformation> bookList = selectBookByBookType(bookinformationCustom);
                bookinformations.addAll(bookList);
                if (bookinformations.size() < Constants.REC_SUM) {
                    //从点击量前100随便拿基本
                    bookinformationCustom.setLimit(Constants.REC_SUM - bookinformations.size());
                    bookinformationCustom.setSumLimit(Constants.RAN_SELECT * 2);
                    for (Bookinformation book : bookList
                            ) {
                        bookIdList.add(book.getBookinformationid());
                    }
                    bookinformationCustom.setBookIdList(bookIdList);
                    bookList = selectBookByRandom(bookinformationCustom);
                    bookinformations.addAll(bookList);
                }
            }
        }
        baseRespose.setReturnString(bookinformations);
        return baseRespose;
    }

    /**
     * @Author:LiuHao
     * @Date:15:24 2019/5/31
     * 根基标签查询推荐小说 selectBookByLabel
     **/
    public List<Bookinformation> selectBookByLabel(BookinformationCustom bookinformationCustom) {
        List<Bookinformation> bookinformationList = new ArrayList<>();
        //查询该小说点赞最高的两个标签
        List<Integer> labelIdList = booklabelMapper.selectLabelIdList(bookinformationCustom.getBookinformationid());
        if (labelIdList.size() == 0) {
            return bookinformationList;
        }
        bookinformationCustom.setLabelIdList(labelIdList);
        bookinformationList = bookinformationMapper.selectLabelList(bookinformationCustom);
        return bookinformationList;
    }

    /**
     * @Author:LiuHao
     * @Date:15:24 2019/5/31
     * 根据类型推荐小说 selectBookByLabel
     **/
    public List<Bookinformation> selectBookByBookType(BookinformationCustom bookinformationCustom) {
        List<Bookinformation> bookinformationList = new ArrayList<>();
        bookinformationList = bookinformationMapper.selectBookByBookType(bookinformationCustom);
        return bookinformationList;
    }

    /**
     * @Author:LiuHao
     * @Date:15:24 2019/5/31
     * 随机拿推荐小说 selectBookByRandom
     **/
    public List<Bookinformation> selectBookByRandom(BookinformationCustom bookinformationCustom) {
        List<Bookinformation> bookinformationList = new ArrayList<>();
        bookinformationList = bookinformationMapper.selectBookByRandom(bookinformationCustom);
        return bookinformationList;
    }

    /**
     * @Author:LiuHao
     * @Date:15:24 2019/5/31
     * 增加用户阅读时长 addUserReadTime
     **/
    public BaseRespose addUserReadTime(BaseRequest baseRequest) {
        log.info("增加用户阅读时长,参数为{}", JSON.toJSONString(baseRequest));
        BaseRespose baseRespose = new BaseRespose();
        Userinformationdet userinformation = null;
        try {
            userinformation = JSON.parseObject(JSON.toJSONString(baseRequest.getRequestString()), Userinformationdet.class);
        } catch (Exception e) {
            throw new ServiceException(ServiceCodeEnum.INFO_IS_FAIL, JSON.toJSONString(baseRequest));
        }
        if (ObjectUtils.isEmpty(userinformation.getReadlength())) {
            throw new ServiceException(203020, "阅读时长不能为空", JSON.toJSONString(baseRequest));
        }
        userinformation.setUserid(baseRequest.getUserId());
        userinformationdetMapper.updateReadTime(userinformation);
        //插入或更新阅读时间段
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MINUTE, 0 - userinformation.getReadlength().intValue() - 2);
        Readtime readtime = new Readtime();
        readtime.setUserid(baseRequest.getUserId());
        readtime.setEndtime(calendar.getTime());
        readtime = readtimeMapper.selectLastByUser(readtime);
        if (ObjectUtils.isEmpty(readtime)) {
            readtime = new Readtime();
            readtime.setEndtime(new Date());
            readtime.setUserid(baseRequest.getUserId());
            calendar.setTime(new Date());
            calendar.add(Calendar.MINUTE, 0 - userinformation.getReadlength().intValue());
            readtime.setStarttime(calendar.getTime());
            readtime.setReadtime(userinformation.getReadlength().intValue());
            readtimeMapper.insertSelective(readtime);
        } else {
            readtime.setEndtime(new Date());
            Long time = (readtime.getEndtime().getTime() - readtime.getStarttime().getTime()) / 60 / 1000;
            readtime.setReadtime(time.intValue());
            readtimeMapper.updateByPrimaryKeySelective(readtime);
        }
        baseRespose.setReturnString(" ");
        return baseRespose;
    }

    /**
     * @Author:LiuHao
     * @Date:15:24 2019/7/01
     * 根据类型和标签搜索书籍 selectBookByTypeAndLabel
     **/
    public BaseRespose selectBookByTypeAndLabel(BaseRequest baseRequest) {
        log.info("根据类型和标签搜索书籍,参数为{}", JSON.toJSONString(baseRequest));
        BaseRespose baseRespose = new BaseRespose();
        BookTypeLabel bookTypeLabel = null;
        try {
            bookTypeLabel = JSON.parseObject(JSON.toJSONString(baseRequest.getRequestString()), BookTypeLabel.class);
        } catch (Exception e) {
            throw new ServiceException(ServiceCodeEnum.INFO_IS_FAIL, JSON.toJSONString(baseRequest));
        }

        if (ObjectUtils.isEmpty(bookTypeLabel.getBooktypeid())) {
            throw new ServiceException(203020, "请选择所要查询的类型", JSON.toJSONString(baseRequest));
        }

        List<Bookinformation> bookinformationList = bookinformationMapper.selectBookByTypeAndLabel(bookTypeLabel);
        baseRespose.setReturnString(bookinformationList);
        return baseRespose;
    }
}
